package com.liholin.springboot.sample.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;

import java.util.Calendar;
import java.util.Map;

public class JWTUtil {
    // 用于JWT进行签名加密的秘钥
    private static String SECRET = "code-duck-*%#@*!&";

    @Value("${springBootTest.jwtExpires}")
    private static int jwtExpires = 180;



    /**
     * @Param: 传入需要设置的payload信息
     * @return: 返回token
     */
    public static String generateToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();

        // 将map内的信息传入JWT的payload中
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        // 设置JWT令牌的过期时间为60
        Calendar instance = Calendar.getInstance();
//        instance.add(Calendar.SECOND, 60);
        //instance.add(Calendar.DATE, 7);
        instance.add(Calendar.MINUTE, jwtExpires);
        builder.withExpiresAt(instance.getTime());

        // 设置签名并返回token
        return builder.sign(Algorithm.HMAC256(SECRET)).toString();
    }

    /**
     * @Param: 传入token
     * @return:
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * @Param: 传入token
     * @return: 解密的token信息
     */
    public static DecodedJWT getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * 解析jwt
     * @param jsonWebToken
     * @param base64Security
     * @return
     */
//    public static Claims parseJWT(String jsonWebToken, String base64Security) {
//        try {
//            Claims claims = Jwts.parser()
//                    .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
//                    .parseClaimsJws(jsonWebToken).getBody();
//            return claims;
//        } catch (ExpiredJwtException  eje) {
//            log.error("===== Token过期 =====", eje);
//            throw new CustomException(ResultCode.PERMISSION_TOKEN_EXPIRED);
//        } catch (Exception e){
//            log.error("===== token解析异常 =====", e);
//            throw new CustomException(ResultCode.PERMISSION_TOKEN_INVALID);
//        }
//    }
}
